#include "RtRoot.h"

#include <QCoreApplication>

RtRoot RtObject::root_;

RtRoot::RtRoot(void) : RtObject("rt","root object")
{
}

RtRoot::~RtRoot(void)
{
    foreach(RtObject* obj, children()) obj->detach();
    /*{
		RtObject* rtobj = qobject_cast<RtObject*>(obj);
		if (rtobj) 
		{
			rtobj->detach();
			delete rtobj;
		}
    }*/
}

void RtRoot::objectCreation(RtObject* obj, bool create)
{
	if (obj==this) return;
	if (obj->parent()==0) return;

	if (create)
		emit objectCreated(obj);
	else 
		emit objectDeleted(obj);
}

void RtRoot::postError(RtObject* obj, const RtErrorEntry &e)
{
	auto_lock L(errorSinkLock);
	foreach(QObject* o, errorSinks)
		QCoreApplication::postEvent(o, new RtErrorEvent(obj, e));
}

void RtRoot::addErrorSink(QObject* s)
{
	auto_lock L(errorSinkLock);
	if (!errorSinks.contains(s)) errorSinks.push_back(s);
}
void RtRoot::removeErrorSink(QObject* s)
{
	auto_lock L(errorSinkLock);
	errorSinks.removeOne(s);
}

QString RtRoot::xml()
{
    QString ret;
    return ret;
}

RtObject* RtRoot::createObject(const QString& name, const QString& className)
{
    RtObject* obj = 0;
    object_map_t::iterator it = object_map_.find(className);
    const QMetaObject* metaObj = (it==object_map_.end()) ? 0 : *it;
    if (metaObj)
    {
        obj = (RtObject*)(metaObj->newInstance(Q_ARG(QString,name)));
		if (!obj)
			this->throwScriptError("The object could not be created");
    }
    return obj;
}

QStringList RtRoot::objectClassNames()
{
    QStringList lst;
    for(object_map_t::iterator it = object_map_.begin(); it!=object_map_.end(); it++)
        lst << it.key();
    return lst;
}

void RtRoot::registerClass(const QMetaObject* metaObj)
{
    object_map_[metaObj->className()] = metaObj;
}



